package com.game.game.service.room;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.game.common.Transmitter;
import com.game.common.constants.GlobalConstants;
import com.game.core.net.common.RemoteNode;
import com.game.core.service.ServiceContainer;
import com.game.game.service.server.ServerService;
import com.game.message.proto.room.RoomProtoBuf.GBRoomStateREQ;

public class RoomHelper
{
	private static CountDownLatch latch = null;
	private final static Lock lock = new ReentrantLock();
	
	public static RoomState getRoomStates()
	{
		
		try
		{
			lock.lock();
			RoomState.getInstance().setPositiveRoomCount(0);
			RoomState.getInstance().setSlientRoomCount(0);
			
			ServerService serverService = ServiceContainer.getInstance().getPublicService(ServerService.class);
			Map<Integer, RemoteNode> battleNodes = serverService.getBattleNodes();
			latch = new CountDownLatch(battleNodes.size());
			
			GBRoomStateREQ.Builder builder = GBRoomStateREQ.newBuilder();
			for (RemoteNode remoteNode : battleNodes.values())
			{
				Transmitter.getInstance().write(remoteNode, GlobalConstants.DEFAULT_CALLBACK, builder.build());
			}
			
			try
			{
				latch.await(2000, TimeUnit.MILLISECONDS); // 超时不会抛异常
				return RoomState.getInstance();
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			return null;
		}
		
		finally
		{
			lock.unlock();
		}
	}
	
	/*
	 * 只能在BGRoomState中调用，不然会有并发问题，导致房间数不准确
	 */
	public static void addRoomState(int slientRoomCount, int positiveRoomCount)
	{
		RoomState.getInstance().setPositiveRoomCount(positiveRoomCount);
		RoomState.getInstance().setSlientRoomCount(slientRoomCount);
		latch.countDown();
	}
}
